package com.jade.modules.media.impl;

import java.io.*;

import javax.inject.Inject;
import javax.inject.Named;

import com.jade.framework.base.lang.Hex;
import com.jade.framework.base.log.Log;
import com.jade.framework.base.log.LogUtils;
import com.jade.framework.base.util.FileTypeUtils;
import com.jade.framework.base.util.ImageUtils;
import com.jade.framework.base.vfile.VFileConstants;
import com.jade.framework.base.vfile.VFileInfo;
import com.jade.framework.base.vfile.VFileUtils;
import com.jade.modules.media.CMediaItem;
import com.jade.modules.media.MediaException;
import com.jade.modules.media.MediaItemManager;
import com.jade.modules.media.MediaLocalService;
import org.apache.commons.lang3.StringUtils;

/**
 * 该服务接口需要本地调用，主要市用于上传和下载媒体资料。
 */
//@Named ("module_mediaLocalService")
public class LocalServiceImpl
        implements MediaLocalService
{
    private MediaItemManager itemManager;
    private Log log = LogUtils.getLog(LocalServiceImpl.class);

//    @Inject
    public void setItemManager(@Named ("module_mediaItemManager") MediaItemManager itemManager)
    {
        this.itemManager = itemManager;
    }

    public CMediaItem uploadMedia(String type, String app, String contentType, String name, InputStream is,
                                  String remark)
            throws MediaException, IOException
    {

        contentType = StringUtils.isNotBlank(contentType) ? contentType : FileTypeUtils.getContentType(name);
        if (StringUtils.isBlank(type)) {
            //根据类型来获取
            if (StringUtils.startsWith(contentType, CMediaItem.TYPE_IMAGE)) {
                type = VFileConstants.DATA_TYPE_IMAGE;
            } else if (StringUtils.startsWith(contentType, CMediaItem.TYPE_VIDEO)) {
                type = VFileConstants.DATA_TYPE_VIDEO;
            } else if (StringUtils.startsWith(contentType, CMediaItem.TYPE_VOICE)) {
                type = VFileConstants.DATA_TYPE_VOICE;
            } else if (StringUtils.startsWith(contentType, CMediaItem.TYPE_VOICE)) {
                type = VFileConstants.DATA_TYPE_SOFTWARE;
            } else {
                type = VFileConstants.DATA_TYPE_FILE;
            }
        }

        //原始图片上传，应当放在临时目录下面比较好
        VFileInfo fileInfo = VFileUtils.uploadFile(type, contentType, name, is);
        CMediaItem item = new CMediaItem();
        item.setUri(fileInfo.getFileId());
        item.setName(fileInfo.getFileName());
        item.setSize(fileInfo.getSize());
        item.setContentType(contentType);
        if (StringUtils.isNotBlank(app)) {
            item.setApp(app);
        }
        item.setType(type);
        item.setRemark(remark);
        itemManager.addItem(item);
        return item;

    }

    public CMediaItem uploadMedia(String type, String app, File file, String remark)
            throws MediaException, IOException
    {
        return uploadMedia(type, app, null, file.getName(), new FileInputStream(file), remark);
    }

    public void downloadMedia(CMediaItem item, OutputStream os)
            throws MediaException, IOException
    {
        VFileUtils.downloadFile(item.getType(), item.getUri(), os);
    }

    public void downloadMedia(CMediaItem item, OutputStream os, long offset, long length)
            throws MediaException, IOException
    {
        VFileUtils.downloadFile(item.getType(), item.getUri(), os, offset, length);
    }

    public File resizeImage(CMediaItem item, int width, int heigth)
            throws MediaException, IOException
    {
        //针对图片的情况
        File file = getCacheFile(item, width, heigth);
        if (!file.exists()) {
            //下载原始图片
            File srcFile = getCacheFile(item, 0, 0);
            if (!srcFile.exists()) {
                VFileUtils.downloadFile(item.getType(), item.getUri(), srcFile);
            }
            //转换图片
            log.info("Resize image " + item.getUri() + "to " + file.getPath() + "  w=" + width + " h=" + heigth);
            ImageUtils.getThumbImage2(srcFile, file, null, width, heigth);
        }

        log.debug("Resized image:" + file.getPath());
        return file;
    }

    protected String cachePath = "/jade/var/cache/media";
    protected int dirCount = 256;

    public void setCachePath(String cachePath)
    {
        this.cachePath = cachePath;
    }

    public void setDirCount(int dirCount)
    {
        this.dirCount = dirCount;
    }

    protected File getCacheFile(CMediaItem item, int width, int height)
    {
        int hashCode = Math.abs(item.getUri().hashCode());
        int index = hashCode % dirCount;
        String name = item.getUri();
        name = name.replace(File.separatorChar, '_');
        String str = String.format("%s/%s/%d/%s_%d_%d", cachePath, item.getApp(), index, name, width, height);
        File file = new File(str);
        file.getParentFile().mkdirs();
        return file;
    }

    public String getAccessUrl(String type, String uri)
    {
        return VFileUtils.getVFileURI(type, uri);
    }

    public String getAccessUrl(CMediaItem item)
    {
        return getAccessUrl(item.getType(), item.getUri());
    }
}

